package android_dhbw.gpx;

import java.io.File;
import java.text.NumberFormat;
import de.dhbw.GpsTools.AdvancedTrack;
import de.dhbw.GpsTools.GpxHandler;
import DHBW.BT.BluetoothDHBW;
import DHBW.BT.PedelecFrame;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;



public class OverviewActivity extends Activity{
	
	private TextView txtv_distance;
	private TextView txtv_elevation;
	private TextView txtv_energy;
	private TextView txtv_status;
	private TextView txtv_current;
	private TextView txtv_voltage;
	private TextView txtv_capacity1;
	private TextView txtv_capacity2;
	
	private SharedPreferences prefs;
	
	private Button btn_loadRoute;
	private Button btn_getConnection;
	
	protected static final int REQUEST_CODE_PICK_FILE_TO_OPEN = 1;
	protected static final int REQUEST_CODE_PICK_FILE_TO_SAVE = 2;
	protected static final int REQUEST_CODE_PICK_DIRECTORY = 3;	
	
    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 11;
    private static final int REQUEST_ENABLE_BT = 12;
    private static final int REQUEST_SETTINGS_SAVED = 13;
    
    private static final int OPTIONS_BUTTON = 21;
    
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothDHBW mBluetoothDHBW = null;
	
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.overviewlayout);
        
        txtv_distance = (TextView)findViewById(R.id.overview_txtv_distance);
        txtv_elevation = (TextView)findViewById(R.id.overview_txtv_elevation);
        txtv_energy = (TextView)findViewById(R.id.overview_txtv_energy);
        txtv_status = (TextView)findViewById(R.id.overview_txtv_status);
        txtv_current = (TextView)findViewById(R.id.overview_txtv_current);
        txtv_voltage = (TextView)findViewById(R.id.overview_txtv_voltage);
        txtv_capacity1 = (TextView)findViewById(R.id.overview_txtv_capcity1);
        txtv_capacity2 = (TextView)findViewById(R.id.overview_txtv_capcity2);
        
        btn_loadRoute = (Button)findViewById(R.id.overview_btn_loadRoute);
        btn_getConnection = (Button)findViewById(R.id.overview_btn_getConnection);
        
        btn_loadRoute.setOnClickListener(loadRouteListener);
        btn_getConnection.setOnClickListener(connectBTListener);
        
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, getString(R.string.overview_bt_not_available), Toast.LENGTH_LONG).show();
            //finish();
            return;
        }
        
        mBluetoothDHBW = new BluetoothDHBW(this,mHandler);
        
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
        }
    }
    
    @Override
    public void onStart() {
        super.onStart();

    }
    
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
      menu.add(0,OPTIONS_BUTTON ,1,getString(R.string.overview_options_settings));  
      return super.onCreateOptionsMenu(menu);  
    }  
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
     switch(item.getItemId())
     {
     case OPTIONS_BUTTON:
    	 Intent myIntent = new Intent(this.getBaseContext(), OptionsActivity.class);
         startActivityForResult(myIntent, REQUEST_SETTINGS_SAVED);
      return true;

     }
     return super.onOptionsItemSelected(item);

    }
	private OnClickListener loadRouteListener = new OnClickListener(){
		public void onClick(View v){
			try{
	    		Intent intent = getIntent("com.estrongs.action.PICK_FILE",getString(R.string.overview_es_load_file));
	    		startActivityForResult(intent, REQUEST_CODE_PICK_FILE_TO_OPEN);
	    	} catch (ActivityNotFoundException e) {
	    		try{
	    		Intent intent = new Intent("org.openintents.action.PICK_FILE");
	    		startActivityForResult(intent, REQUEST_CODE_PICK_FILE_TO_OPEN);
	    		}
	    		catch (ActivityNotFoundException ex){
	    			loadRoute("/sdcard/test.gpx");
	    		}
	    	}
		}
	};
	
	private OnClickListener connectBTListener = new OnClickListener(){
		public void onClick(View v){
           Intent serverIntent = new Intent(OverviewActivity.this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
		}
	};
	
    private Intent getIntent(String action,String btnTitle){
    	
    	Intent intent = new Intent(action);
    	
    	if (btnTitle != null)
    		intent.putExtra("com.estrongs.intent.extra.BUTTON_TITLE", btnTitle);
		
		return intent ;
    }
    
	private void loadRoute(String path){
		AdvancedTrack track;
		
		File file = new File(path);
		
		if (file.exists())
		{
			GpxHandler tools = new GpxHandler(path);
			tools.readGpx();

			track = tools.getTracks().get(0);
			processTrack( track );
		}
		else
		{
			Toast.makeText(this, getString(R.string.overview_es_not_installed), Toast.LENGTH_SHORT).show();
		}
	}
	
	private void processTrack( AdvancedTrack track )
	{
		SuppCalculator suppCalc;
		prefs = this.getSharedPreferences("android_dhbw.gpx", Context.MODE_PRIVATE);
		
		NumberFormat nf_dist = NumberFormat.getInstance();
		nf_dist.setMaximumFractionDigits(2);
		nf_dist.setGroupingUsed(false);
		
		NumberFormat nf_energy = NumberFormat.getInstance();
		nf_energy.setMaximumFractionDigits(0);
		nf_energy.setGroupingUsed(false);
		
		double wTotal = prefs.getFloat("WTOTAL", (float) 609000);
		double rollCoeff = prefs.getFloat("ROLLRESISTANCE", (float) 0.0045);
		double aeroCoeff = prefs.getFloat("AERORESISTANCE", (float) 0.9);
		double veloAVG = prefs.getFloat("AVGVELOCITY", (float) 7.0);
		double massDriver = prefs.getFloat("DRIVERMASS", (float) 70.0);
		double massBike = prefs.getFloat("BIKEMASS", (float) 20.0);
		double frontSurface = prefs.getFloat("FRONTSURFACE", (float) 0.5);
		
		suppCalc = new SuppCalculator(track);
		suppCalc.setParameters(wTotal, rollCoeff, aeroCoeff, veloAVG, massDriver, massBike, frontSurface);
		suppCalc.processTrack();
		((Globals) this.getApplication()).gpxTrack = track;
		
		txtv_distance.setText(String.valueOf(nf_dist.format(track.getOverallDistance())) + "m");
		txtv_elevation.setText(String.valueOf(nf_dist.format(track.getPositiveElevation())) + "m");
		txtv_energy.setText(String.valueOf(nf_energy.format(suppCalc.getPotentialEnergy()))+ "J");
	}
	
    /**
     * This is called after the ES File Manager finished.
     */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != RESULT_OK || data == null) {
			return ;
		}
		
		Uri uri = data.getData();
		
		switch (requestCode) {
			case REQUEST_CODE_PICK_FILE_TO_OPEN:
				if (uri != null) {
					loadRoute(uri.getPath());
				}				
				break;
			case REQUEST_CODE_PICK_FILE_TO_SAVE:
				if (uri != null) {
				}				
				break;
			case REQUEST_CODE_PICK_DIRECTORY:
				break;
	        case REQUEST_CONNECT_DEVICE:
	            // When DeviceListActivity returns with a device to connect
	            if (resultCode == Activity.RESULT_OK) {
	                // Get the device MAC address
	                String address = data.getExtras()
	                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
	                // Get the BLuetoothDevice object
	                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
	                // Attempt to connect to the device
	                mBluetoothDHBW.connect(device);
	            }
	            break;
	        case REQUEST_SETTINGS_SAVED:
	        	if (((Globals) this.getApplication()).gpxTrack != null)
	        	{
	        		processTrack(((Globals) this.getApplication()).gpxTrack);
	        	}
	        	
		}
	}

    /**
     * The Handler that gets information back from the BluetoothChatService
     */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	
        	NumberFormat nf_btValues = NumberFormat.getInstance();
        	nf_btValues.setMaximumFractionDigits(3);
        	//nf_btValues.setMinimumFractionDigits(3);
        	nf_btValues.setGroupingUsed(false);
    		
            switch (msg.what) {
            case BluetoothDHBW.MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case BluetoothDHBW.STATE_CONNECTED:
             		txtv_status.setText(getString(R.string.overview_bt_connected));
                	break;
                case BluetoothDHBW.STATE_CONNECTING:
                    
                	break;
                case BluetoothDHBW.STATE_NONE:
             		txtv_status.setText(getString(R.string.overview_bt_not_connected));
                	break;
                }
                break;
            case BluetoothDHBW.MESSAGE_NOTICE:

            	break;
            case BluetoothDHBW.MESSAGE_NEW:
            	PedelecFrame tmpData = (PedelecFrame) msg.obj;
            	int cycle1 = 1; 

             	if (tmpData.id() % cycle1 == 0) {
             		txtv_current.setText(nf_btValues.format(Double.toString((double)tmpData.current())));
             		txtv_voltage.setText(nf_btValues.format(Double.toString((double) tmpData.voltage() / 30)));
             		txtv_capacity1.setText("RPM: "+nf_btValues.format(Double.toString((double)tmpData.rpm()*128)));
             		txtv_capacity2.setText("ID: "+nf_btValues.format(Double.toString((double)tmpData.id())));
             	}
             	break;
            }
        }
    };
	
}
